<?php
namespace Home\Controller;

use Think\Controller;
use Think\Verify;

class LoginController extends Controller
{
    /**
     * 用户登录页面
     * @author Mr.Alien
     * @return  string
     */
    public function index()
    {
        session('id') && $this->redirect('Index/index');
        $this->display();
    }

    /**
     * 验证用户的登录
     * @author Mr.Alien
     * @return string
     */
    public function login()
    {
        $data = I('post.');
        $verify = new Verify();
        !$verify->check($data['code']) && $this->error('验证码有误');
        $has = M('User')->where(array('name'=>$data['name'],'pass'=>md5($data['pass'])))->find();
        !$has && $this->error('用户名或密码错误');
        ($has['status'] == 1) && $this->error('用户已被禁用');
        $this->setSession($has);
        $this->success('登录成功');
    }

    /**
     * 用户退出登录
     * @author Mr.Alien
     * @return string
     */
    public function logout()
    {
        session(null);
        $url = U('Login/index');
        echo "<script>parent.location.href = '{$url}' </script>";
    }

    /**
     * 设置session
     * @author Mr.Alien
     * @return string
     */
    private function setSession($data)
    {
        foreach($data as $key => $value){
            session($key,$value);
        }
    }
}